﻿using System;
using System.Collections;
using UnityEngine;
using YooAsset;

namespace Gp.Scripts.Core.Res
{
    public class ResPackageManager : MonoBehaviour
    {
        private bool _isInit = false;
        private const string DEFAULT_PACKAGE_NAME = "DefaultPackage";
        public static ResourcePackage ResPackage => _instance._package;
        private static ResPackageManager _instance;
        private ResourcePackage _package;

        public void Init()
        {
            if (_instance != null) return;
            _instance = this;
            _instance.InternalInit();
        }

        private void InternalInit()
        {
            if (_isInit) return;

            _isInit = true;
            YooAssets.Initialize();
            _package = YooAssets.CreatePackage(DEFAULT_PACKAGE_NAME);
            YooAssets.SetDefaultPackage(_package);
            
        }

        public IEnumerator InitPackage(Action callback)
        {
            yield return InitBuildProcess();
            yield return InitVersionProcess();
            callback?.Invoke();
        }

        private IEnumerator InitBuildProcess()
        {
            var buildPipeline       = EDefaultBuildPipeline.BuiltinBuildPipeline; 
            var simulateBuildResult = EditorSimulateModeHelper.SimulateBuild(buildPipeline, "DefaultPackage");
            var editorFileSystem    = FileSystemParameters.CreateDefaultEditorFileSystemParameters(simulateBuildResult);
            var initParameters      = new EditorSimulateModeParameters
            {
                EditorFileSystemParameters = editorFileSystem
            };

            var initOperation = _package.InitializeAsync(initParameters);
            yield return initOperation;
            if(initOperation.Status == EOperationStatus.Succeed)
                Debug.Log("资源包初始化成功！");
            else 
                throw new Exception($"资源包初始化失败：{initOperation.Error}");
        }
        

        private IEnumerator InitVersionProcess()
        {
            var operation = _package.RequestPackageVersionAsync();
            yield return operation;

            if (operation.Status == EOperationStatus.Succeed)
            {
                //更新成功
                string packageVersion = operation.PackageVersion;
                
                Debug.Log($"Request package Version : {packageVersion}");
                
                var op = _package.UpdatePackageManifestAsync(packageVersion);
                yield return op;

                if (op.Status != EOperationStatus.Succeed)
                {
                    Debug.LogError(op.Error);
                }
            }
            else
            {
                //更新失败
                Debug.LogError(operation.Error);
            }
        }
        
        
        public static void Coroutine(IEnumerator cor)
        {
            _instance.StartCoroutine(cor);
        }
    }
}